﻿using System;
using System.Device.Location;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SydEnergiPrototype.DataAccess
{
    public class GpsService : IGpsService, IDisposable
    {
        private readonly GeoCoordinateWatcher _geoCoordinateWatcher;
        public event EventHandler PositionChanged;
        
        private GeoCoordinate _currentPosition;
        public GeoCoordinate CurrentPosition
        {
            get
            {
                if(_currentPosition == null)
                    _currentPosition = new GeoCoordinate();

                return _currentPosition;
            }
            private set { _currentPosition = value; }
        }

        public GpsService()
        {
            _geoCoordinateWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
            _geoCoordinateWatcher.PositionChanged += GeoCoordinateWatcherOnPositionChanged;
            _geoCoordinateWatcher.Start();
        }

        private void GeoCoordinateWatcherOnPositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> args)
        {
            lock (CurrentPosition)
            {
                CurrentPosition.Latitude = args.Position.Location.Latitude;
                CurrentPosition.Longitude = args.Position.Location.Longitude;
            }

            if (PositionChanged != null)
                PositionChanged(this, null);
        }

        public void Dispose()
        {
            if(_geoCoordinateWatcher != null)
                _geoCoordinateWatcher.Stop();
        }
    }
}
